import React, { useState } from "react";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { Button, Form, Input, Upload, message } from "antd";
import type { UploadProps, RcFile } from "antd/es/upload";
import { update } from '../../../domain/userInfo/service';
import { Upload as AWSUpload } from "@aws-sdk/lib-storage";
import { S3 } from "@aws-sdk/client-s3";
import useBearStore from "@/store";
import { getUserInfo } from "../../../domain/userInfo/service";
// 类型定义
interface MinioConfig {
  endpoint: string;
  bucket: string;
  accessKey: string;
  secretKey: string;
  region: string;
}

interface FormValues {
  nickName?: string;
  email?: string;
  signature?: string;
  hobbies?: string;
}

// MinIO 配置
const MINIO_CONFIG: MinioConfig = {
  endpoint: "http://114.55.105.248:9000",
  bucket: "verynb",
  accessKey: "liyumin",
  secretKey: "20030312lymA",
  region: "us-east-1"
};

// 初始化S3客户端 (AWS SDK v3)
const s3 = new S3({
  endpoint: MINIO_CONFIG.endpoint,
  credentials: {
    accessKeyId: MINIO_CONFIG.accessKey,
    secretAccessKey: MINIO_CONFIG.secretKey
  },
  region: MINIO_CONFIG.region,
  forcePathStyle: true
});

const PersonalForm: React.FC<{ onClose: () => void }> = ({ onClose }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>("");
  const [minioUrl, setMinioUrl] = useState<string>("");
  const { setId,setEmail,setHeadPic,setNickName,setPhoneNumber,setUserName,setHobbies,setSignature} = useBearStore();
  // 文件上传前校验
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("只能上传 JPG/PNG 文件!");
      return Upload.LIST_IGNORE;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片必须小于2MB!");
      return Upload.LIST_IGNORE;
    }
    return isJpgOrPng && isLt2M;
  };

  // 自定义上传实现 (AWS SDK v3)
  const customRequest: UploadProps['customRequest'] = async (options) => {
    const { file, onProgress, onSuccess, onError } = options;
    setLoading(true);

    try {
      const uploadFile = file as RcFile;
      const fileName = `avatars/${Date.now()}_${uploadFile.name}`;

      // 使用 AWS SDK v3 的 Upload 类
      const parallelUpload = new AWSUpload({
        client: s3,
        params: {
          Bucket: MINIO_CONFIG.bucket,
          Key: fileName,
          Body: uploadFile,
          ContentType: uploadFile.type
        }
      });

      // 添加进度监听
      parallelUpload.on("httpUploadProgress", (progress) => {
        if (progress.total&& progress.loaded) {
          onProgress?.({ 
            percent: Math.round((progress.loaded / progress.total) * 100) 
          });
        }
      });

      // 执行上传
      await parallelUpload.done();

      const fileUrl = `${MINIO_CONFIG.endpoint}/${MINIO_CONFIG.bucket}/${fileName}`;
      setMinioUrl(fileUrl);
      
      onSuccess?.({ 
        url: fileUrl,
        name: uploadFile.name,
        size: uploadFile.size,
        status: "done"
      }, uploadFile);
      
      message.success("上传成功");
    } catch (err) {
      console.error("上传失败:", err);
      onError?.(err instanceof Error ? err : new Error("上传失败"));
      message.error("上传失败");
    } finally {
      setLoading(false);
    }
  };

  // 文件变化处理
  const handleChange: UploadProps["onChange"] = (info) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      const reader = new FileReader();
      reader.onload = () => setImageUrl(reader.result as string);
      reader.readAsDataURL(info.file.originFileObj as RcFile);
      setLoading(false);
    }
  };

  // 表单提交
  const onFinish = async (values: FormValues) => {
    try {
      const res = await update({ 
        ...values, 
        headPic: minioUrl 
      });
      
      if (res.data.code === 201) {
        message.success("更新成功");
        //获取用户信息，更新仓库的数据
        const userInfo = await getUserInfo();
        if(userInfo.data.data.id){
          setId(userInfo.data.data.id);
          setEmail(userInfo.data.data.email)
          setHeadPic(userInfo.data.data.headPic)
          setNickName(userInfo.data.data.nickName)
          setPhoneNumber(userInfo.data.data.phoneNumber)
          setUserName(userInfo.data.data.username)
          setHobbies(userInfo.data.data.hobbies)
          setSignature(userInfo.data.data.signature)
        }
        onClose();
      } else {
        message.error(res.data.message || "更新失败");
      }
    } catch (err) {
      console.error("提交失败:", err);
      message.error("提交失败");
    }
  };

  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传头像</div>
    </button>
  );

  return (
    <Form form={form} onFinish={onFinish} layout="vertical">
      <div style={{ textAlign: "center", marginBottom: 24 }}>
        <Upload
          name="avatar"
          listType="picture-circle"
          showUploadList={false}
          beforeUpload={beforeUpload}
          customRequest={customRequest}
          onChange={handleChange}
        >
          {imageUrl ? (
            <img
              src={imageUrl}
              alt="avatar"
              style={{ 
                width: "100%", 
                height: "100%", 
                borderRadius: "50%", 
                objectFit: "cover" 
              }}
            />
          ) : (
            uploadButton
          )}
        </Upload>
      </div>

      <Form.Item<FormValues> label="用户昵称" name="nickName">
        <Input placeholder="请输入昵称" />
      </Form.Item>

      <Form.Item<FormValues> label="电子邮箱" name="email">
        <Input placeholder="请输入邮箱" type="email" />
      </Form.Item>

      <Form.Item<FormValues> label="个性签名" name="signature">
        <Input.TextArea placeholder="请输入您的个性签名" rows={3} />
      </Form.Item>

      <Form.Item<FormValues> label="兴趣爱好" name="hobbies">
        <Input.TextArea placeholder="请输入您的兴趣爱好" rows={3} />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" block>
          提交
        </Button>
      </Form.Item>
    </Form>
  );
};

export default PersonalForm;